package com.accloud.cloudservice;

import com.accloud.common.ACConfiguration;
import com.accloud.service.ACException;
import com.accloud.service.ACMsg;
import com.accloud.utils.ACUtils;
import com.accloud.utils.LogUtil;
import com.accloud.utils.SecurityUtils;
import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;
import com.qiniu.android.common.Constants;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.conn.ConnectTimeoutException;

public class ACServiceSyncClient {
    private static final String TAG = "ACServiceClient";
    private ACMsg req;
    private String routerAddr;
    private String serviceName;
    private int serviceVersion;

    public ACServiceSyncClient(String serviceName2, int serviceVersion2, String routerAddr2, ACMsg req2) {
        this.req = req2;
        this.serviceName = serviceName2;
        this.serviceVersion = serviceVersion2;
        this.routerAddr = routerAddr2;
    }

    private String getFullUrl(String service, int version, String addr) {
        return addr + "/" + service + "/v" + String.valueOf(version) + "/" + this.req.getName();
    }

    public ACMsg postData() throws ACException {
        InputStream streamPayload;
        String urlStr = getFullUrl(this.serviceName, this.serviceVersion, this.routerAddr);
        String payloadFormat = this.req.getPayloadFormat();
        LogUtil.d(TAG, payloadFormat);
        int length = this.req.getPayloadSize();
        byte[] payload = this.req.getPayload();
        if (payloadFormat == null) {
            try {
                payload = ACObjectMarshaller.marshal(this.req);
                payloadFormat = "application/x-zc-object";
                length = payload.length;
                this.req.setPayload(payload, payloadFormat);
            } catch (Exception e) {
                throw new ACException(ACException.MARSHAL_ERROR, e.getMessage());
            }
        }
        if (payloadFormat == null || (!payloadFormat.equals("application/octet-stream") && !payloadFormat.equals("application/x-zc-object") && !payloadFormat.equals("text/json"))) {
            throw new ACException(ACException.WRONG_PAYLOAD_FORMAT, "wrong request payload format");
        }
        if (payloadFormat.equals("application/octet-stream")) {
            if (payload == null && (streamPayload = this.req.getStreamPayload()) != null) {
                try {
                    payload = ACUtils.inToBytes(streamPayload);
                    this.req.closeStreamPayload();
                } catch (Exception e2) {
                    throw new ACException(ACException.INTERNAL_ERROR, e2.toString());
                }
            }
            Set<String> keys = this.req.getKeys();
            if (!keys.isEmpty()) {
                urlStr = urlStr + "?";
                Iterator<String> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String value = this.req.get(key).toString();
                    try {
                        if (value.contains(MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR)) {
                            value = URLEncoder.encode(value, Constants.UTF_8);
                        }
                    } catch (UnsupportedEncodingException e3) {
                    }
                    if (iterator.hasNext()) {
                        urlStr = urlStr + key + "=" + value + "&";
                    } else {
                        urlStr = urlStr + key + "=" + value;
                    }
                }
            }
        }
        LogUtil.d(TAG, urlStr);
        if (payloadFormat.equals("application/octet-stream")) {
            LogUtil.d(TAG, Arrays.toString(payload));
        } else {
            LogUtil.d(TAG, new String(payload));
        }
        HttpsURLConnection connection = null;
        try {
            HttpsURLConnection connection2 = (HttpsURLConnection) new URL(urlStr).openConnection();
            connection2.setConnectTimeout(ACConfiguration.CONNECT_TIMEOUT * 1000);
            connection2.setReadTimeout(ACConfiguration.READ_TIMEOUT * 1000);
            connection2.setRequestMethod(HttpPost.METHOD_NAME);
            connection2.setRequestProperty("Content-Type", payloadFormat);
            connection2.setRequestProperty("X-Zc-Content-Length", String.valueOf(length));
            if (this.req.getContext() != null) {
                if (this.req.getContext().getMajorDomain() != null) {
                    connection2.setRequestProperty("X-Zc-Major-Domain", this.req.getContext().getMajorDomain());
                    LogUtil.d("ACHeader", "X-Zc-Major-Domain:" + this.req.getContext().getMajorDomain());
                }
                if (this.req.getContext().getMajorDomainId() != null) {
                    connection2.setRequestProperty("X-Zc-Major-Domain-Id", String.valueOf(this.req.getContext().getMajorDomainId()));
                    LogUtil.d("ACHeader", "X-Zc-Major-Domain-Id:" + this.req.getContext().getMajorDomainId());
                }
                if (this.req.getContext().getSubDomain() != null) {
                    connection2.setRequestProperty("X-Zc-Sub-Domain", this.req.getContext().getSubDomain());
                    LogUtil.d("ACHeader", "X-Zc-Sub-Domain:" + this.req.getContext().getSubDomain());
                }
                if (this.req.getContext().getAccessMode() != null) {
                    connection2.setRequestProperty("X-Zc-Access-Mode", this.req.getContext().getAccessMode());
                    LogUtil.d("ACHeader", "X-Zc-Access-Mode:" + this.req.getContext().getAccessMode());
                }
                if (this.req.getContext().getTraceId() != null) {
                    connection2.setRequestProperty("X-Zc-Trace-Id", this.req.getContext().getTraceId());
                    LogUtil.d("ACHeader", "X-Zc-Trace-Id:" + this.req.getContext().getTraceId());
                }
                if (this.req.getContext().getTraceStartTime() != null) {
                    connection2.setRequestProperty("X-Zc-Trace-Start-Time", this.req.getContext().getTraceStartTime());
                    LogUtil.d("ACHeader", "X-Zc-Trace-Start-Time:" + this.req.getContext().getTraceStartTime());
                }
                if (this.req.getContext().getTimestamp() != null) {
                    connection2.setRequestProperty("X-Zc-Timestamp", this.req.getContext().getTimestamp());
                    LogUtil.d("ACHeader", "X-Zc-Timestamp:" + this.req.getContext().getTimestamp());
                }
                if (this.req.getContext().getTimeout() != null) {
                    connection2.setRequestProperty("X-Zc-Timeout", this.req.getContext().getTimeout());
                    LogUtil.d("ACHeader", "X-Zc-Timeout:" + this.req.getContext().getTimeout());
                }
                if (this.req.getContext().getNonce() != null) {
                    connection2.setRequestProperty("X-Zc-Nonce", this.req.getContext().getNonce());
                    LogUtil.d("ACHeader", "X-Zc-Nonce:" + this.req.getContext().getNonce());
                }
                if (this.req.getContext().getUserId() != null) {
                    connection2.setRequestProperty("X-Zc-User-Id", this.req.getContext().getUserId());
                    LogUtil.d("ACHeader", "X-Zc-User-Id:" + this.req.getContext().getUserId());
                }
                if (this.req.getContext().getSignature() != null) {
                    connection2.setRequestProperty("X-Zc-User-Signature", this.req.getContext().getSignature());
                    LogUtil.d("ACHeader", "X-Zc-User-Signature:" + this.req.getContext().getSignature());
                }
                if (this.req.getContext().getMethodVersion() != null) {
                    connection2.setRequestProperty("X-Zc-Version", String.valueOf(this.req.getContext().getMethodVersion()));
                    LogUtil.d("ACHeader", "X-Zc-Version:" + String.valueOf(this.req.getContext().getMethodVersion()));
                }
                if (this.req.getContext().getPhoneId() != null) {
                    connection2.setRequestProperty("X-Zc-Phone-Id", String.valueOf(this.req.getContext().getPhoneId()));
                    LogUtil.d("ACHeader", "X-Zc-Phone-Id:" + String.valueOf(this.req.getContext().getPhoneId()));
                }
                connection2.setRequestProperty("X-Zc-Device-Os", "android");
                connection2.setRequestProperty("X-Zc-Operation-Type", "app");
            }
            if (payload == null || payload.length <= 0) {
                connection2.connect();
            } else {
                connection2.setDoOutput(true);
                connection2.connect();
                OutputStream os = connection2.getOutputStream();
                os.write(payload);
                os.flush();
                os.close();
            }
            SecurityUtils.validatePinning(connection2);
            if (connection2.getResponseCode() == 200) {
                ACMsg parseClientResp = parseClientResp(connection2);
                connection2.disconnect();
                return parseClientResp;
            }
            LogUtil.d(TAG, "errorCode:" + connection2.getResponseCode() + "  errorMessage:" + connection2.getResponseMessage());
            throw new ACException(connection2.getResponseCode(), connection2.getResponseMessage());
        } catch (ConnectTimeoutException e4) {
            throw new ACException(ACException.TIMEOUT, "connect timeout");
        } catch (SocketTimeoutException e5) {
            throw new ACException(ACException.TIMEOUT, "request timeout");
        } catch (SocketException e6) {
            throw new ACException(ACException.INTERNET_ERROR, "internet error");
        } catch (Exception e7) {
            throw new ACException(ACException.INTERNAL_ERROR, e7.toString());
        } catch (Throwable th) {
            connection.disconnect();
            throw th;
        }
    }

    private ACMsg parseClientResp(HttpURLConnection connection) throws Exception {
        ACMsg resp = new ACMsg();
        String msgName = null;
        Map<String, List<String>> headers = connection.getHeaderFields();
        if (headers != null) {
            for (String key : headers.keySet()) {
                if (key != null) {
                    if (key.toLowerCase().equals(ACMsg.MSG_NAME_HEADER)) {
                        msgName = connection.getHeaderField(key);
                    } else if (key.toLowerCase().startsWith("x-zc-msg-attr_")) {
                        resp.put(key.toLowerCase().substring("x-zc-msg-attr_".length()), connection.getHeaderField(key));
                    }
                    LogUtil.d(TAG, "header:[name:" + key + "---value:" + connection.getHeaderField(key) + "]");
                }
            }
        }
        LogUtil.d(TAG, "msgName:" + msgName);
        if (msgName == null || msgName.equals("")) {
            throw new Exception("no msg name");
        }
        resp.setName(msgName);
        String payloadFormat = connection.getContentType();
        if (payloadFormat == null || (!payloadFormat.equals("application/octet-stream") && !payloadFormat.equals("application/x-zc-object") && !payloadFormat.equals("text/json"))) {
            throw new Exception("invalid payloadFormat");
        }
        LogUtil.d(TAG, "payloadFormat:" + payloadFormat);
        if (connection.getContentLength() <= 0) {
            LogUtil.d(TAG, "content length:0");
            resp.setPayload(new byte[0], payloadFormat);
        } else {
            InputStream in = connection.getInputStream();
            if (in == null) {
                throw new Exception("invalid payload");
            } else if (payloadFormat.equals("application/octet-stream")) {
                resp.setStreamPayload(in, connection.getContentLength());
            } else {
                byte[] content = ACUtils.inToBytes(in);
                if (content == null || content.length == 0) {
                    throw new Exception("invalid payload");
                }
                LogUtil.d(TAG, "payload:" + new String(content));
                LogUtil.d(TAG, "setPayload");
                resp.setPayload(content, payloadFormat);
                if (payloadFormat.equals("application/x-zc-object")) {
                    LogUtil.d(TAG, "start-unmarshal");
                    ACObjectMarshaller.unmarshal(resp, content);
                }
            }
        }
        return resp;
    }
}
